﻿using System.Runtime.CompilerServices;
using System.IO.Compression;
using System.Text;
using System.Collections;


#region 委托
class Program5
{
    public delegate void SimpleDelegate(int x, int y);
    public static void Main(){

        SimpleDelegate simple = new SimpleDelegate(sum);
        simple += muitil;
        simple(1, 2);

        SimpleDelegate simple2 = sum;
        simple2 += muitil;
        simple2(3, 4);

        Action<string> action = msg => Console.WriteLine(msg);
        action("this is action delegate");

        Func<int, int, int> func = (a,b) => a*b;
        Console.WriteLine("func :" + func(6, 2));
    }

    static void sum(int x, int y)
    {
        Console.WriteLine("sum :" + (x + y));
    }

    static void muitil(int x, int y)
    {
        Console.WriteLine("mutil :" + (x * y));
    }
}


#endregion



#region 数据集合
public class Program4
{
    //public static void Main(string[] args)
    //{
    //    //ArrayListTest();
    //    //StackTest();
    //    //QueueTest();
    //    HashTableTest();
    //}

    public static void ArrayListTest()
    {
        int[] array = { 1, 4, 5, 6, 4 };
        ArrayList arrayList = new ArrayList();
        arrayList.Add("jjj");
        arrayList.Add(11);
        arrayList.AddRange(array);
        Console.WriteLine(arrayList[2]);
    }

    public static void StackTest()
    {
        Stack<int> st = new Stack<int>();
        st.Push(1);
        Console.WriteLine(st.Pop());

        Stack st1 = new Stack();
        st1.Push(2);
        st1.Push("ss");
        st1.Push("dd");
        Console.WriteLine(st1.Pop());
        Console.WriteLine(st1.Pop());
        Console.WriteLine(st1.Contains(2));
        Console.WriteLine(st1.Contains(1));
    } 

    public static void QueueTest()
    {
        Queue<int> queue = new Queue<int>();
        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(3);
        queue.Enqueue(4);
        queue.Enqueue(5);
        queue.Enqueue(6);
        queue.Enqueue(7);
        queue.Enqueue(8);
        queue.Enqueue(9);
        queue.Enqueue(10);

        int top = queue.Dequeue();
        Console.WriteLine("queue top:" + top);
        Console.WriteLine("queue is exist number 3 :" + queue.Contains(3));
        int[] array = queue.Where(t => t % 2 == 0).ToArray();
    }

    public static void HashTableTest()
    {
        Hashtable ht = new Hashtable();
        ht.Add("key1", 1);
        ht.Add("key2", 2);
        ht.Add("key3", "val3");

        int[] arr = new int[] {1,4 ,3 };
        ht.Add("key4", arr);

        ht.Remove("key1");

        ht["key3"] = 2;

        Console.WriteLine(ht["key3"]);
        Console.WriteLine(ht.ContainsKey("key5"));
        Console.WriteLine(ht.Contains("key4"));
        Console.WriteLine(ht.ContainsValue(2));
        Console.WriteLine("count :" + ht.Count);

        foreach(var item in ht.Values)
        {
            Console.WriteLine(item);
        }
    }
}


#endregion


#region STring
public class Progrm3
{
    //public static void Main()
    //{
    //    string str = "this is a test code! this is a character ### {0}";
    //    //string str2 = string.Format(str, " sss");
    //    string str3 = str.Replace("this", "those");
    //    string[] str4 = str.Split(new char[] { '!' });
        
    //    Console.WriteLine(str4[0] + "\n" + str4[1]);
    //}
}

    
#endregion


#region 异步编程
public class Program2
{
    //public static async Task Main()
    //{
    //    Task task = Task.Run(() =>
    //    {
    //        int a = 1 + 1;
    //        Console.WriteLine(a);
    //    });
    //    await task;

    //    Task<int> task2 = Task.Run(async () =>
    //    {
    //        await Task.Delay(1000);
    //        return 2 + 2;
    //    });
    //    await task2.ContinueWith(t => { Console.WriteLine(t.Result); });

    //    Task<int> task4 = Task.Run(() =>
    //    {
    //        int sum = 0;
    //        for (int i = 0; i < 100; i++)
    //        {
    //            sum += i;
    //        }
    //        return sum;
    //    });

    //    int sum = task4.Result;
    //    Console.WriteLine(sum);

    //    string ret = await FooAsync();
    //    Console.WriteLine("等待着...");
    //    Console.WriteLine(ret);
    //    Console.WriteLine("完成");
    //}

    private static async Task<string> FooAsync()
    {
        Console.WriteLine("等待3s...");
        await Task.Delay(3000);
        return "FooAsync done";
    }

    private string Foo()
    {
        Thread.Sleep(1000);
        return "Foo done";
    }
}
#endregion


#region 解压缩

class Program1
{
    //static void Main(string[] args)
    //{
    //    // Qt 压缩后的 Base64 字符串
    //    string qtCompressedData = "eJzz9jE1djI18XIyMDAxsjRz1vH31jGyMAJRCgoKFnoGYJaBnqG5MVhKz9LCVdfAEsSGIC5vJBMsDdBNMEMywQRigpkRmgkAev0cnw==";

    //    // 解压
    //    string originalText = ZlibHelper.DecompressWithZLibHeader(qtCompressedData);
    //    Console.WriteLine(originalText); // 输出原始内容
    //}

}


public class ZlibHelper
{
    // .NET 6+ 专用（完全兼容 zlib 格式）
    public static string DecompressWithZLibHeader(string compressedBase64)
    {
        byte[] compressedData = Convert.FromBase64String(compressedBase64);

        using (var outputStream = new MemoryStream())
        using (var compressedStream = new MemoryStream(compressedData))
        using (var zlibStream = new ZLibStream(compressedStream, CompressionMode.Decompress))
        {
            zlibStream.CopyTo(outputStream);
            return Encoding.UTF8.GetString(outputStream.ToArray());
        }
    }
}

#endregion


#region 事件机制使用场景
/// <summary>
/// 事件机制-使用场景示例
/// </summary>
public class CarInfo : EventArgs
{
    //停车的开始时间
    public DateTime StartTime { get; set; }
    //停车的结束时间
    public DateTime EndTime { get; set; }
    //车牌
    public string LicensePlate { get; set; }
}
public class SnapInfo
{
    //车牌标志，拍到车牌说明有车；反之无车
    public string LicensePlate { get; set; }
}
/// <summary>
/// 发布者
/// </summary>
public class Camera
{
    public event EventHandler<CarInfo> OnSnapLicenseEvent;
    //模拟摄像机循环在抓拍车牌
    public void SnapPhoto()
    {
        Task.Run(() =>
        {
            List<string> license = new List<string>()
                { "","","","沪A11111", "沪B22222","沪C33333","","" };
            Random random = new Random();
            while (true)
            {
                Thread.Sleep(1000);
                int index = random.Next(1, license.Count + 1);
                SnapInfo snapInfo = new SnapInfo() { LicensePlate = license[index - 1] };
                //当车牌不为空的时候表示车来了
                if (!string.IsNullOrEmpty(snapInfo.LicensePlate))
                {
                    Console.WriteLine($"抓拍到车牌{snapInfo.LicensePlate}！");
                    OnSnapLicense(GetCarInfoBySnapInfo(snapInfo));

                }
                else
                {
                    Console.WriteLine("当前没有抓拍到车牌！");
                    Console.WriteLine("--------------------------------------");
                }
            }
        });
    }
    public CarInfo GetCarInfoBySnapInfo(SnapInfo snapInfo)
    {
        //抓拍到车牌后，这里直接赋值，相当于模拟通过接口车牌查询了该车的进场数据
        CarInfo carInfo = new CarInfo()
        {
            StartTime = DateTime.Parse("2023-08-03 12:00:00"),
            EndTime = DateTime.Now,
            LicensePlate = snapInfo.LicensePlate,
        };
        return carInfo;
    }
    public void OnSnapLicense(CarInfo carInfo)
    {
        OnSnapLicenseEvent?.Invoke(this, carInfo);
    }
}
/// <summary>
/// 订阅者
/// </summary>
//收费员（负责收费）
public class Charger
{
    //收费
    public void Charge(object sender, CarInfo carInfo)
    {
        Console.WriteLine($"收费员：对{carInfo.LicensePlate}完成了收费");
    }
}
//闸机（负责开关）
public class Gate
{
    public void OpenGate(object sender, CarInfo carInfo)
    {
        Console.WriteLine($"闸机对：{carInfo.LicensePlate}车辆放行");
    }
}

//class Program
//{
//    static void Main(string[] args)
//    {
//        //先分析需求：车到车库门口，摄像机要拍照到车牌后,收费员收费,闸机抬杆
//        Camera camera = new Camera();
//        Charger charger = new Charger();
//        Gate gate = new Gate();
//        camera.OnSnapLicenseEvent += charger.Charge;
//        camera.OnSnapLicenseEvent += gate.OpenGate;
//        camera.SnapPhoto();
//        Console.ReadLine();
//    }

//}

#endregion

#region 异步事件介绍
/// <summary>
/// 异步事件使用介绍
/// </summary>
public class Demo
{
    public event EventHandler DemoEvent;
    public void Raise()
    {
        try
        {
            //3修改Raise函数，让事件的触发处在我们自定义的同步上下文内。
            this.DemoEvent?.NaiveRaiseAsync(this, EventArgs.Empty).GetAwaiter().GetResult();
            Console.WriteLine("所有的事件处理已经被执行！");
        }
        catch (Exception ex)
        {
            Console.WriteLine("事件处理中发生异常！", ex.Message);
        }
    }
}

//class Test
//{
//    //主程序调用
//    static void Main(string[] args)
//    {
//        var instance = new Demo();
//        //采用匿名订阅异步事件
//        instance.DemoEvent += async (sendr, args) =>
//        {
//            Console.WriteLine("异步事件1执行开始");
//            await Task.Delay(10);
//            Console.WriteLine("异步事件1执行结果");

//        };
//        //传统的订阅异步事件
//        instance.DemoEvent += method2;
//        instance.DemoEvent += (sender, args) =>
//        {
//            Console.WriteLine("执行事件1!");
//        };
//        instance.DemoEvent += (sender, args) =>
//        {
//            Console.WriteLine("执行事件2!");
//        };
//        Console.WriteLine("*开始发起事件!");
//        instance.Raise();
//        Console.WriteLine("*事件执行完毕，继续下一项工作!");
//        Console.ReadLine();
//    }

//    //异步方法
//    static async void method2(object sender, EventArgs e)
//    {
//        Console.WriteLine("异步事件2执行开始");
//        await Task.Delay(100);
//        Console.WriteLine("异步事件2执行完毕");
//    }
//}

//1实现同步上下文（对异步的分裂点进行标记）
public class NaiveSynchronizationContext : SynchronizationContext
{
    private readonly Action completed;
    public NaiveSynchronizationContext(Action completed)
    {
        this.completed = completed;
    }
    public override SynchronizationContext CreateCopy()
    {
        return new NaiveSynchronizationContext(this.completed);
    }
    public override void OperationStarted()
    {
        Console.WriteLine("同步上下文: 开始");
    }
    public override void OperationCompleted()
    {
        Console.WriteLine("同步上下文: 完成");
        this.completed();
    }
}
//2对NaiveExtension函数进行扩展
public static class NaiveExtension
{
    public static Task NaiveRaiseAsync(this EventHandler @this, object sender, EventArgs eventArgs)
    {
        // 如果没有事件处理，那么立即结束
        if (@this == null)
        {
            return Task.CompletedTask;
        }
        var delegates = @this.GetInvocationList();
        var count = delegates.Length;

        var tcs = new TaskCompletionSource<bool>();
        foreach (var @delegate in @this.GetInvocationList())
        {
            // 检查AsyncStateMachineAttribute属性，判断是否异步处理函数
            var async = @delegate.Method.GetCustomAttributes(typeof(AsyncStateMachineAttribute), false).Any();

            // 定义 'completed' action
            var completed = new Action(() =>
            {
                if (Interlocked.Decrement(ref count) == 0)
                {
                    tcs.SetResult(true);
                }
            });

            if (async)
            {
                SynchronizationContext.SetSynchronizationContext(new NaiveSynchronizationContext(completed));
            }

            @delegate.DynamicInvoke(sender, eventArgs);

            if (!async)
            {
                // 如果不是异步，手工调用完成
                completed();
            }
        }
        return tcs.Task;
    }
}

#endregion